import __config from './config'
import Dialog from '@vant/weapp/dialog/dialog';
// token 白名单
function whiteList(url) {
	let list = [
		//登录接口
    (url == '/weixin/api/ma/wxuser/login'),
    (url == '/weixin/api/ma/goodsspu/findNdCategory'),
    (url == '/weixin/api/ma/goodsspu/findCategoryFirstData'),
    (url == '/weixin/api/ma/goodsspu/slideshowPage')
	]
	let bol = false
	for (const item of list) {
		if (item) {
			bol = true
		}
	}
	return bol
}
//请求
function request(method, url ,data) {
  return new Promise(function (resolve, reject) {
    const sessionKey = wx.getStorageSync('sessionKey')||null
    let header = {
        'app-id': wx.getAccountInfoSync().miniProgram.appId,
        'thirdSessionKey': sessionKey != null ?sessionKey : ''
    }
   if(sessionKey==null&&!whiteList(url)){
    wx.showModal({
      title: '提示',
      content: '授权登录',
      success: res=> {
        if (res.confirm) {
          getApp().doLogin()
        } else if (res.cancel) {
        }
      }
    })  
   }else{
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: __config.basePath + url,
      method: method,
      data: data,
      header: header,
      timeout:20000,
      success(res) {
        //请求成功
          // console.log(res)
          // 登录失效
          if(res.data.code==4399){
            wx.showToast({
              title: '登录失效',
              icon:"none"
            })
            wx.setStorageSync('sessionKey', null)
            wx.setStorageSync('name', null)
            wx.setStorageSync('avatarUrl', null)
            wx.reLaunch({
              url: getApp().getCurrentPageUrlWithArgs(),
            })
          }
          resolve(res.data);
      },
      fail(err) {
        //请求失败
        wx.showToast({
          title: '网络错误！',
          icon:"error"
        })
        reject(err)
      },
      complete(){
        wx.hideLoading() 
      }
    })
   } 
  })
}
//接口可以集合到一块，集中管理
module.exports = {
  request
}